package com.teach.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.teach.entity.ResponseEntity;
import com.teach.entity.TbRole;
import com.teach.entity.TbUser;
import com.teach.entity.TbUserRole;
import com.teach.mapper.TbUserRoleMapper;
import com.teach.service.TbUserService;
import com.teach.mapper.TbUserMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
    implements TbUserService{
    @Resource
    private TbUserMapper tbUserMapper;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private TbUserRoleMapper tbUserRoleMapper;

    @Override
    public ResponseEntity login(TbUser tbUser) {
        String token=null;
        Map<String,Object> map=new HashMap<>();

        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(tbUser.getUname()),"uname",tbUser.getUname());
        List<TbUser> userList = tbUserMapper.selectList(wrapper);
        if(userList.size()<=0){
            return new ResponseEntity(null,500,"用户名或密码错误",false);
        }
        for (TbUser user : userList) {
            if(!user.getUpwd().equals(tbUser.getUpwd())){
                return new ResponseEntity(null,500,"用户名或密码错误",false);
            }
            token = Jwts.builder().setId(user.getId()+"").setSubject(user.getRname())
                    .signWith(SignatureAlgorithm.HS256,"huangyujie")
                    .compact();
            map.put("token",token);
            map.put("user",user);
        }
        //讲token放入redis中
        redisTemplate.opsForValue().set("token",token,5, TimeUnit.MINUTES);
        return new ResponseEntity(map,200,"登录成功",true);
    }

    @Override
    public ResponseEntity userList(TbUser tbUser) {
        //用户列表以及模糊查询
        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(tbUser.getPhone()),"phone",tbUser.getPhone());
        List<TbUser> userList = tbUserMapper.selectList(wrapper);
        return new ResponseEntity(userList,200,"查询成功",true);
    }

    @Override
    public ResponseEntity userSave(TbUser tbUser,String token) {
            //判断手机号是否存在
            QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
            wrapper.eq(StringUtils.isNotBlank(tbUser.getPhone()),"phone",tbUser.getPhone());
            List<TbUser> userList = tbUserMapper.selectList(wrapper);
            if(userList.size()>0){
                return new ResponseEntity(null,500,"该手机号已经存在",false);
            }
            try {
                //先添加用户表
                tbUserMapper.insert(tbUser);
                //设置角色
                List<TbUserRole> tbUserRoles = tbUser.getTbUserRoles();
                for (TbUserRole tbUserRole : tbUserRoles) {
                    tbUserRole.setUserId(tbUser.getId());
                    //添加中间表
                    tbUserRoleMapper.insert(tbUserRole);
                }
            }catch (Exception e){
                e.printStackTrace();
                return new ResponseEntity(null,500,"添加失败",false);
            }
        return new ResponseEntity(null,200,"添加成功",false);
    }

    @Override
    public ResponseEntity updatePwd(TbUser tbUser,String token) {
        //更新密码
        TbUser user = new TbUser();
        user.setId(tbUser.getId());
        user.setUpwd(tbUser.getUpwd());
        tbUserMapper.updateById(user);
        return new ResponseEntity(null,200,"更新密码成功",true);
    }

    @Override
    public ResponseEntity userDel(TbUser tbUser,String token) {
        Boolean flag=false;
        List<Map> list=new ArrayList<>();
        //解析token
        Claims claims = Jwts.parser().setSigningKey("huangyujie").parseClaimsJws(token).getBody();
        int uid = Integer.parseInt(claims.getId());
        //根据登录人的id判断是否有权限
        List<Map> mapList = tbUserMapper.selectByUid(uid);
        for (Map map : mapList) {
            //二级名称
            String fname = (String) map.get("fname");
            int indexOf = fname.indexOf("用户管理");
            if(indexOf !=-1){
                //根据登录人的id和二级名称查询三级的名称
                list = tbUserMapper.selectConunt(uid,fname);
            }
        }
        //判断是否有删除的权限
        for (Map map : list) {
            //三级名称
            String gname= (String) map.get("gname");
            //判断是否有删除权限
            if((gname.indexOf("删除"))!=-1){
                flag=true;
            }
        }
        if(flag){
           //先查询中间表
            List<TbUserRole> userRoleList = tbUserRoleMapper.selectByUid(tbUser.getId());
            for (int i = 0; i < userRoleList.size(); i++) {
                TbUserRole tbUserRole = userRoleList.get(i);
                //先删除附表
                tbUserRoleMapper.deleteById(tbUserRole.getId());
            }
            //添加附表
            List<TbUserRole> tbUserRoles = tbUser.getTbUserRoles();
            for (TbUserRole tbUserRole : tbUserRoles) {
                tbUserRole.setUserId(tbUser.getId());
                //添加
                tbUserRoleMapper.insert(tbUserRole);
            }
            //删除(修改)主表
            TbUser user = new TbUser();
            user.setId(tbUser.getId());
            user.setState(tbUser.getState());
            tbUserMapper.updateById(user);
        }
        return new ResponseEntity(null,200,"删除成功",true);
    }
}




